﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.Configuration;
using System.Web;
using System.IO;

namespace Core.DS
{
    public static partial class CourseDesign
    {
        public static dynamic package(int cid, string sid,bool isCls)
        {
            if (!isCls)
            {
                var sql = new Sql.SqlDataContext();
                string filepath = packageOne(sid);
                if (filepath == "User不存在" || filepath == "Student不存在" || filepath == "此学生未上传课程设计")
                    return new
                    {
                        success = false,
                        msg = filepath
                    };
                return new
                {
                    success = true,
                    filepath = filepath
                };
            }
            else
            {
                var sql = new Sql.SqlDataContext();
                var allstudent = sql.DSClassStudent.Where(row => row.cid == cid);
                foreach (var st in allstudent)
                {
                    packageOne(st.sid);
                }
                var clsStr = sql.DSClass.FirstOrDefault(row => row.cid == cid).title;
                string patch = string.Format("{0}\\CourseDesign\\{1}\\", ConfigurationManager.AppSettings["SafePath"], clsStr);
                if (!Directory.Exists(patch))
                {
                    return new
                    {
                        success = false,
                        msg = "此班级的学生都未上传课程设计"
                    };
                }
                functional.rar(patch, string.Format("\\{0}\\{1}", ConfigurationManager.AppSettings["RARPath"], clsStr), clsStr);
                return new
                {
                    success = true,
                    filepath = string.Format("{0}.zip", clsStr)
                };
            }

        }
        public static string packageOne(string sid)
        {
            var sql = new Sql.SqlDataContext();
            var s = sql.DSClassStudent.FirstOrDefault(row => row.sid == sid);
            var clsStr = sql.DSClass.FirstOrDefault(row => row.cid == s.cid).title;
            string patch = string.Format("{0}\\CourseDesign\\{1}\\{2}\\", ConfigurationManager.AppSettings["SafePath"], clsStr, s.sid);
            if (!Directory.Exists(patch))
            {
                return "此学生未上传课程设计";
            }
            var rarpath = string.Format("{0}\\{1}", ConfigurationManager.AppSettings["RARPath"], clsStr);
            if(!Directory.Exists(rarpath))
            {
                Directory.CreateDirectory(rarpath);
            }
            functional.rar(patch, rarpath, s.sid);
            return string.Format("RARPath/{0}/{1}.rar", clsStr, s.sid);
        }
    }
}
